package edu.zjucst.spb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.zjucst.spb.conf.FileConfig;
import edu.zjucst.spb.dao.mapper.FileMapper;
import edu.zjucst.spb.domain.ResponseResult;
import edu.zjucst.spb.domain.entity.TbFile;
import edu.zjucst.spb.enums.FileTypeEnum;
import edu.zjucst.spb.enums.PrivilegeEnum;
import edu.zjucst.spb.service.FileService;
import edu.zjucst.spb.util.FileUtil;
import edu.zjucst.spb.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

import static edu.zjucst.spb.enums.OptStatusEnum.UPLOAD_ERROR;
import static edu.zjucst.spb.enums.OptStatusEnum.UPLOAD_FORBIDDEN;

/**
 * 文件操作的service层
 *
 * @author zxz
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    FileMapper fileMapper;

    @Autowired
    FileConfig fileConfig;

    @Override
    public ResponseResult<Object> upload(MultipartFile file, Integer privilege) {
        String fileName = file.getOriginalFilename();
        assert fileName != null;

        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String path     = fileConfig.getSavePath() + File.separator + fileName;
        try {
            if (!FileUtil.upload(file, path)) {
                return ResponseResult.error(UPLOAD_FORBIDDEN);
            }
        } catch (IOException e) {
            return ResponseResult.error(UPLOAD_ERROR);
        }

        TbFile tbfile = new TbFile();
        tbfile.setName(fileName);
        tbfile.setType(FileTypeEnum.getCodeByName(fileType));
        tbfile.setPath(path);
        tbfile.setPrivilege(privilege);
        tbfile.setCreatorId(SessionUtil.getUserId());
        fileMapper.insert(tbfile);
        return ResponseResult.success("上传成功");
    }

    @Override
    public List<TbFile> listPublicFiles() {
        LambdaQueryWrapper<TbFile> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TbFile::getPrivilege, PrivilegeEnum.PUBLIC.getCode());
        return fileMapper.selectList(lqw);
    }

    @Override
    public TbFile getFileById(int id) {
        return fileMapper.selectById(id);
    }
}
